package com.xckj.cycling.utils

import android.content.Intent
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.xckj.cycling.framework.BaseActivityKt

/**
 * 谷歌登录
 */
class GoogleLoginUtils(activity: BaseActivityKt) : BaseLoginUtil(activity) {
    companion object {
        private const val SERVER_CLIENT_ID =
            "199159291456-frtsln2gcq9oq5b4eca5nmsgc12f5fuq.apps.googleusercontent.com"
    }


    private val mGso: GoogleSignInOptions = GoogleSignInOptions.Builder().requestEmail()
        .requestIdToken(SERVER_CLIENT_ID).requestServerAuthCode(SERVER_CLIENT_ID)
        .build()
    private val client = GoogleSignIn.getClient(activity, mGso)
    private val signInIntent: Intent = client.getSignInIntent()

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 1000) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            try {
                val account = task.getResult(ApiException::class.java)
                if (account != null) {
                    viewModel.loginByGoogle(account) {
                        if (!it.isSuccessful) {
                            activity.showMessage("Server error ${it.code}  ${it.msg} ")
                        }
                        activity.hideDialog()
                    }
                } else {
                    activity.showMessage("account is null ")
                }
            } catch (e: ApiException) {
                activity.hideDialog()
                e.printStackTrace()
                // The ApiException status code indicates the detailed failure reason.
                // Please refer to the GoogleSignInStatusCodes class reference for more information.
            }
        }
    }

    override fun startLogin() {
        activity.startActivityForResult(signInIntent, 1000)
    }

    override fun onDestroy() {
    }
}